package cn.mall.goods.service.impl;

import cn.hutool.json.JSONObject;
import cn.mall.base.constants.BaseConstants;
import cn.mall.base.utils.PageList;
import cn.mall.goods.domain.Goods;
import cn.mall.goods.dto.ExamineDTO;
import cn.mall.goods.mapper.GoodsMapper;
import cn.mall.goods.query.GoodsQuery;
import cn.mall.goods.service.IGoodsService;
import cn.mall.base.service.impl.BaseServiceImpl;
import cn.mall.org.domain.Shop;
import cn.mall.org.mapper.ShopMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jarvis-Smith
 * @since 2023-12-04
 */
@Service
public class GoodsServiceImpl extends BaseServiceImpl<Goods> implements IGoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ShopMapper shopMapper;


    @Override
    public void update(Goods goods){
        String result = processString(goods.getGoodsImg());
        goods.setGoodsImg("http://webshopdonw.com/pic/"+result);
        goodsMapper.update(goods);
    }

    /**
     * 新增商品
     *
     * @param goods
     */
    @Override
    public void insert(Goods goods) {
        if(goods.getType() == 8 ){
            String remarks = goods.getRemarks();
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                JsonNode jsonNode = objectMapper.readTree(remarks);
                System.out.println(jsonNode.toString());
                JsonNode sFminqty = jsonNode.get("sFminqty");
                int sfmin = sFminqty.asInt();
                JsonNode sFmaxqty = jsonNode.get("sFmaxqty");
                int sfmax = sFmaxqty.asInt();
                JsonNode sCminqty = jsonNode.get("sCminqty");
                int scmin = sCminqty.asInt();
                JsonNode sCmaxqty = jsonNode.get("sCmaxqty");
                int scmax = sCmaxqty.asInt();
                JsonNode sGminqty = jsonNode.get("sGminqty");
                int sgmin = sGminqty.asInt();
                JsonNode sGmaxqty = jsonNode.get("sGmaxqty");
                int sgmax = sGmaxqty.asInt();
                if(StringUtils.isEmpty(goods.getName()) || StringUtils.isEmpty(goods.getType()) || StringUtils.isEmpty(goods.getShop().getId())){
                    throw new RuntimeException("请填写所有信息");
                }
                if(sfmin>=sfmax || scmin>=scmax || sgmin>=sgmax){
                    throw new RuntimeException("设置的最小数量大于最大数量");
                }
                Goods goods2 = new Goods();
                BeanUtils.copyProperties(goods, goods2);
                goods2.setShopId(goods.getShop().getId());
                goods2.setAuditstate(BaseConstants.Goods.STATE_WAIT_GOODS_NOAUTID);
                goods2.setState(BaseConstants.Goods.STATE_WAIT_GOODS_OFFSHELF);
                /// www/wwwroot/wb_mall/dist/pic/1.jpg
                String result = processString(goods.getGoodsImg());
                goods2.setGoodsImg("http://webshopdonw.com/pic/"+result);
                goodsMapper.insert(goods2);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else {
            // 所有参数的非空校验
            if (StringUtils.isEmpty(goods.getName()) || StringUtils.isEmpty(goods.getPrice()) || StringUtils.isEmpty(goods.getType()) || StringUtils.isEmpty(goods.getShop().getId())) {
                throw new RuntimeException("请填写所有信息");
            }
//        Goods goods1 = goodsMapper.loadByShopIdAndType(goods.getShop().getId(), goods.getType());
//        if (Objects.nonNull(goods1)){
//            throw new RuntimeException("新增该商品已存在");
//        }
            if(goods.getMinqty()>=goods.getMaxqty()){
                throw new RuntimeException("设置的最小数量大于最大数量");
            }
            Goods goods2 = new Goods();
            BeanUtils.copyProperties(goods, goods2);
            goods2.setShopId(goods.getShop().getId());
            goods2.setAuditstate(BaseConstants.Goods.STATE_WAIT_GOODS_NOAUTID);
            goods2.setState(BaseConstants.Goods.STATE_WAIT_GOODS_OFFSHELF);
            /// www/wwwroot/wb_mall/dist/pic/1.jpg
            String result = processString(goods.getGoodsImg());
            goods2.setGoodsImg("http://webshopdonw.com/pic/"+result);
            goodsMapper.insert(goods2);
        }
    }

    /**
     * 商品上架
     *
     * @param ids
     * @return
     */
    @Override
    public String onSale(List<Long> ids) {
        // 非空校验
        if (ids == null || ids.size() == 0) {
            throw new RuntimeException("未选中数据，请重新选择");
        }
        // 根据ids查询所有符合条件的数据
        List<Goods> goods = goodsMapper.loadByIds(ids, 1);
        if (goods == null || goods.size() == 0) {
            throw new RuntimeException("你选择的不是下架的商品数据");
        }
        // 修改数据库状态
        // 获取所有符合条件的商品的 id 数组
        List<Long> goodsIds = goods.stream().map(item -> item.getId()).collect(Collectors.toList());
        // 上架
        goodsMapper.updateState(goodsIds, 0);

        // 结果信息
        String msg = "共提交了%s条上架数据，成功了%s条，失败了%s条";
        msg = String.format(msg, ids.size(), goods.size(), (ids.size() - goods.size()));

        // 返回数据
        return msg;
    }

    /**
     * 商品下架
     *
     * @param ids
     * @return
     */
    @Override
    public String offSale(List<Long> ids) {
        // 非空校验
        if (ids == null || ids.size() == 0) {
            throw new RuntimeException("未选中数据，请重新选择");
        }
        // 修改数据库状态
        goodsMapper.updateState(ids, 1);
        // 结果信息
        String msg = "共提交了%s条下架数据";
        msg = String.format(msg, ids.size());

        // 返回结果
        return msg;
    }

    /**
     * 手动审核
     *
     * @param examineDTO
     */
    @Override
    public void manualAudit(ExamineDTO examineDTO) {
        // 审核商品先看该店铺是否为可用状态
        Goods goods = goodsMapper.loadById(examineDTO.getId());
        Shop shop = shopMapper.loadById(goods.getShopId());
        if (shop.getState() != BaseConstants.ShopAudit.STATE_NORMAL) {
            throw new RuntimeException("该商品所在店铺未通过审核，请先审核该商品所在店铺");
        }
        goods.setAuditstate(examineDTO.getAuditstate());
        // 修改数据库状态
        goodsMapper.update(goods);
    }

    @Override
    public PageList<Goods> newpageList(GoodsQuery query) {

        long total = goodsMapper.loadTotalByuser(query);
        if (total > 0){
            List<Goods> rows = goodsMapper.pageListByuser(query);
            return new PageList<Goods>(total, rows);
        }
        return new PageList<>();
    }

    @Override
    public PageList<Goods> pageListV2(GoodsQuery query) {
        long total = goodsMapper.loadTotalV2(query);
        if (total > 0){
            List<Goods> rows = goodsMapper.pageListv2(query);
            return new PageList<Goods>(total, rows);
        }
        return new PageList<>();
    }

    public static String processString(String original) {
        int lastIndexOfSlash = original.lastIndexOf("/");
        if (lastIndexOfSlash != -1) {
            return original.substring(lastIndexOfSlash + 1);
        } else {
            // 如果原始字符串中没有斜杠，则返回原始字符串或根据需要处理
            return original;
        }
    }

}
